package com.zhangxin.aiInterview.manager.cos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.zhangxin.aiInterview.common.ErrorCode;
import com.zhangxin.aiInterview.config.CosClientConfig;

import java.io.File;
import java.net.URL;
import javax.annotation.Resource;

import com.zhangxin.aiInterview.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

/**
 * Cos 对象存储操作
 */
@Component
@Slf4j
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;

    /**
     * 上传对象
     *
     * @param key           唯一键
     * @param localFilePath 本地文件路径
     * @return
     */
    public PutObjectResult putObject(String key, String localFilePath) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key,
                new File(localFilePath));
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 上传对象
     *
     * @param key  唯一键
     * @param file 文件
     * @return
     */
    public PutObjectResult putObject(String key, File file) {
        // 创建元数据对象
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("application/pdf"); // 设置内容类型
        metadata.setContentDisposition("inline");   // 设置为内嵌展示，而非下载

        // 创建上传请求并带上元数据
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                cosClientConfig.getBucket(), key, file);
        putObjectRequest.setMetadata(metadata);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 生成临时预览链接(带签名)
     * @param key
     * @return
     */
    public URL generatePreviewUrl(String key) {
        // key是对象在存储桶里的路径，比如 ai_interview/resume_pdf/xxxx/xxx.pdf
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(cosClientConfig.getBucket(), key, HttpMethodName.GET);

        // 指定返回头（告诉COS：返回的时候设置这两个头）
        req.addRequestParameter("response-content-type", "application/pdf");
        req.addRequestParameter("response-content-disposition", "inline");

        // 生成带签名的URL
        return cosClient.generatePresignedUrl(req);
    }

    /**
     * 删除对象
     *
     * @param key 图片路径（唯一标识）
     * @throws CosClientException
     * @throws CosServiceException
     */
    public void deleteObject(String key) {
        try {
            cosClient.deleteObject(cosClientConfig.getBucket(), key);
        } catch (Exception e) {
            log.error("删除对象失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除对象失败");
        }
    }
}
